import DataCenter from "../GlobalData/DataCenter";
import Tips from "../Tools/Tips";
import KeyCodeMap from "../Tools/keyCodeMap";
import TransTime from "../Tools/TransTime";
import player_controller from "../Elements/player_controller";
import { PlayerState, RequestCode, GameAction } from "../GlobalData/DataStruct";
import game_over_panel from "../Elements/game_over_panel";
import SocketInstance from "../Tools/SocketInstance";

export default class game_scene extends Laya.Script {
    constructor() { super(); }

    private static TIME_INTERVAL=20      //时间频率

    private count_time:number=5          //倒计时
    private isShiftDown:boolean=false    //是否按下Shift键
    private isShiftUsed:boolean=false    //是否已经按下Shift键
    private charArry:Array<string>=['Hello','World','apple','banana','orange','peach','coconut','peanut']   //字符串数组
    private wordIdx:number=0             //字符串数组索引
    private charIdx:number=0             //字符索引
    private curSelWord:string            //当前字符串
    private isBegin:boolean=false        //游戏是否开始
    private isOver:boolean=false         //游戏是否结束
    private usedTime:number=0            //已使用的时间
    private valid_num:number=0           //正确的个数
    private total_num:number=1           //总的个数
    private right:number=0               //正确率
    private rate:number=0                //速度
    private player:player_controller     //玩家控制器
    private computer:player_controller   //电脑控制器
    private player_distance:number       //玩家路程

    private show_text:Laya.Text          //显示文本
    private input_text:Laya.Text         //输入文本
    private bottom_panel:Laya.Sprite     //底部显示栏节点
    private circle_panel:Laya.Sprite     //圆形面板
    private right_text:Laya.Text         //正确率文本
    private rate_text:Laya.Text          //速度文本
    private time_text:Laya.Text          //计时文本
    private bg_sprite:Laya.Sprite        //背景节点
    private gameOver_panel:Laya.Sprite   //结束面板节点
    private gameOver_panel_controller:game_over_panel    //结束面板控制器
    private ctrl_array=[]                //人物控制器数组

    onEnable(): void 
    {
        //初始化变量
        this.initParams()
        //初始化事件
        this.initEvent()
        //倒计时
        this.countDown()

        //初始化字符串
        this.reCreateWord()

        for(let i=0;i<DataCenter.members.length;i++)
        {
            console.log("loading character")
            console.log(DataCenter.members[i])
            console.log("------------------")
            let temp=new player_controller()
            if(DataCenter.user_name==DataCenter.members[i].name)
            {
                temp.initPlayer(45,458,this.owner,true,"player",
                                    DataCenter.members[i].name,
                                    DataCenter.members[i].id)
                this.player=temp
            }
            else
            {
                temp.initPlayer(50,375,this.bg_sprite,false,"comp",
                                    DataCenter.members[i].name,
                                    DataCenter.members[i].id)
                this.ctrl_array.push(temp)
            }

        }



        // //创建电脑控制器,跟随bg_sprite(背景节点)移动
        // this.computer=new player_controller()
        // this.computer.initPlayer(50,375,this.bg_sprite,false,"comp")


        // //测试动态加载玩家
        // this.player=new player_controller()
        // this.player.initPlayer(45,458,this.owner,true,"player")
        //初始化玩家距离
        this.player_distance=45
    }
    /**初始化事件 */
    initEvent()
    {
        //游戏结束的监听
        Laya.stage.on("game_over",this,this.gameOver)
        Laya.stage.on("move",this,this.move_callback)
        Laya.stage.on("over",this,this.over_callback)
    }
    /**游戏结束回调函数 */
    over_callback(data:any)
    {
        if(data.state==0)
        {
            Tips.instance.showTips(data.msg,this.owner)
        }
        else
        {
            if(DataCenter.user_name!=data.rankList.member[0].name)
            {
                this.gameOver(true,false)
            }
            else
            {
                this.gameOver(true,true)
            }
            
        }
    }
    /**移动回调函数 */
    move_callback(data:any)
    {
        for(let i=0;i<this.ctrl_array.length;i++)
        {
            if(this.ctrl_array[i].player_id==data.id)
            {
                //控制玩家移动
                (this.ctrl_array[i] as player_controller).Move()
            }
        }
    }

    checkTime()
    {
        //累加时间计时
        this.usedTime+=(game_scene.TIME_INTERVAL/1000)
        //转换成string显示到舞台
        this.time_text.text="时间："+TransTime.transTime(Number(this.usedTime.toFixed(2))

    }

    /**游戏结束控制 */
    gameOver(isShow:boolean,isWin:boolean)
    {
        // console.log(str)
        // console.log(n)
        //初始化结束面板
        if(isShow)
        {
            
            this.gameOver_panel.visible=true
            this.gameOver_panel_controller.initPanel(
                this.time_text.text,
                this.rate_text.text,
                "正确率："+this.right_text.text,
                isWin
            )
        }

        //暂停计时
        Laya.stage.clearTimer(this,this.checkTime)
        //游戏状态
        this.isOver=true
        //将电脑玩家暂停
    }


    /**初始化变量 */
    initParams()
    {
        //获取底部显示栏节点
        this.bottom_panel=this.owner.getChildByName("bottom_panel") as Laya.Sprite
        //获取显示文本节点
        this.show_text=this.bottom_panel.getChildByName("show_text") as Laya.Text
        //获取输入文本节点
        this.input_text=this.bottom_panel.getChildByName("input_text") as Laya.Text
        //获取圆形面板
        this.circle_panel=this.bottom_panel.getChildByName("circle_panel") as Laya.Sprite
        //获取正确率文本节点
        this.right_text=this.circle_panel.getChildByName("right_text") as Laya.Text
        //获取时间文本节点
        this.time_text=this.bottom_panel.getChildByName("time_text") as Laya.Text
        //获取速度文本节点
        this.rate_text=this.bottom_panel.getChildByName("rate_text") as Laya.Text
        //获取背景节点
        this.bg_sprite=this.owner.getChildByName("bg_sprite") as Laya.Sprite
        //获取结束面板节点
        this.gameOver_panel=this.owner.getChildByName("game_over_panel") as Laya.Sprite
        //获取结束面板控制器
        this.gameOver_panel_controller=this.gameOver_panel.getComponent(game_over_panel)
    }

    /**重新初始化字符串 */
    reCreateWord()
    {
        //将当前字符串显示到舞台
        this.show_text.text=this.charArry[this.wordIdx]
        //初始化当前字符串
        this.curSelWord=this.charArry[this.wordIdx]
        //初始化字符索引
        this.charIdx=0
        //初始化输入文本对象
        this.input_text.text=""
    }


    /**倒计时 */
    countDown()
    {
        //定时执行countDown_callback
        Laya.stage.timerLoop(1000,this,this.countDown_callback)
    }
    //计时回调函数
    countDown_callback()
    {
        //当倒计时到0时，结束倒计时
        if(this.count_time==0)
        {
            //显示游戏开始
            Tips.instance.showTips(
                "游戏开始",
                this.owner
            );
            //清楚定时器
            Laya.stage.clearTimer(this,this.countDown_callback)
            //修改游戏状态
            this.isBegin=true
            //开始计时
            Laya.stage.timerLoop(
                game_scene.TIME_INTERVAL,
                this,
                this.checkTime
            )
            //开始更新正确率和是速度
            Laya.stage.timerLoop(
                500,
                this,
                function(){
                    //将正确率显示到舞台
                    this.right=((this.valid_num/this.total_num)*100)
                    this.right_text.text=this.right.toFixed(1)+"%"
                    //将速度显示到舞台
                    this.rate=(this.valid_num/this.usedTime)*60
                    this.rate_text.text="速度："+this.rate.toFixed(1)+"字/分"
                }
            )
            // //用定时器定时移动电脑
            // Laya.stage.timerLoop(
            //     1000,
            //     this,
            //     function(){
            //         this.computer.Move()
            //     }
            // )
            return
        }
        //调用全局Tips单例显示倒计时
        Tips.instance.showTips(
            this.count_time.toString(),
            this.owner
        )
        //倒计时自减
        this.count_time--
    }

    /**键盘弹起事件 */
    onKeyUp(e:any)
    {
        //按下Shift键
        if(e.keyCode==16)
        {
            this.isShiftDown=false
        }
    }
    /**键盘按下事件 */
    onKeyDown(e:any)
    {

        if(this.isBegin&&!this.isOver)
        {
            //如果按下的键为16，
            //就将isShiftDown设为false
            if(e.keyCode==16)
            {
                this.isShiftDown=true
                return
            }
            //总数加1
            this.total_num++
            //获取输入键值的字符
            let charInput=KeyCodeMap.getCharFromKeyCode(e.keyCode,this.isShiftDown)
            //如果输入值跟当前字符相同
            if(charInput==this.curSelWord.substr(this.charIdx,1))
            {
                //正确的数量加1
                this.valid_num++
                //同步input_text
                this.input_text.text+=charInput
                //索引往后递推
                this.charIdx++
                //测试move函数
                this.player.Move()
                //发起移动请求
                SocketInstance.instance.sendRequest(
                    RequestCode.GAME,
                    GameAction.MOVE,
                    null
                )
                //获取玩家x坐标
                let playerX=this.player.player_ani.x

                //当玩家x坐标超过500时就移动背景
                if(playerX>500)
                {
                    //使用缓动动画移动背景
                    Laya.Tween.to(
                        this.bg_sprite,
                        {x:this.bg_sprite.x-20},
                        200,
                        null,
                        Laya.Handler.create(this,function(){
                            this.player.player_ani.play(0,true,"idel")
                            this.player.player_state=PlayerState.IDEL
                            //给玩家距离加上20
                            DataCenter.player_distance+=20
                        })
                    )
                }
                //如果当前字符串输入完毕，切换到下一个字符串
                if(this.charIdx==this.curSelWord.length)
                {
                    //切换到随机的字符
                    this.wordIdx=Number((Math.random()*(this.charArry.length-1)).toFixed(0))
                    //重新创建字符串
                    this.reCreateWord()
                }
            }
        }
        else
        {
            this.isOver ? 
            Tips.instance.showTips("游戏已结束",this.owner) :
            Tips.instance.showTips("游戏还未开始",this.owner)                   
        }

        
        //如果超过了2640距离之后将游戏状态设置结束
        if(DataCenter.player_distance>200)
        {
            //进入结束控制
            console.log("game_over");
            this.gameOver(false,false);
            SocketInstance.instance.sendRequest(
                RequestCode.GAME,
                GameAction.OVER,
                null
            )
            
        }
    }


    onDisable(): void {
    }
}